import user from '../../../utils/user.js'
import {
    createInviteCode,
} from '../../../api/app.js'
Page({
    data: {
        name: '',
        company: '',
        code: '0000',
        bra: '00',
        sec: '00',
        projectId: '',
        projectName: '',
        time: '',
        count: 0,
        workers: [],
        timer: '',
    },
    onReady() {
        console.log(user)
        this.setData({
            name: user.userName,
            company: user.companyName
        })
    },
    onLoad(option) {
        this.setData({
            projectId: option.projectId,
            projectName: option.projectName,
        },()=>{
            console.log(this.data.projectId,'projectId')
        })
        this.createInviteCode()
    },
    reCode() {
        this.createInviteCode(true)
    },

    createInviteCode(refresh=false) {
        clearInterval(this.interval)
        createInviteCode({
            projectId: this.data.projectId,
            projectName: this.data.projectName,
            companyId: user.companyId,
            ttl: 10,
            userId: user.userId,
            refresh
        }).then(res => {
            const bra = Math.floor(res.expiredTime/60)
            const sec = res.expiredTime%60
            this.setData({
                code: res.inviteCode,
                bra: bra>9?bra:('0'+bra),
                sec: sec>9?sec:('0'+sec),
            })
            this.interval = setInterval(() => {
                if (Number(this.data.sec) === 0 && Number(this.data.bra) === 0) {
                    clearInterval(this.interval)
                    this.createInviteCode()
                    // 失效
                    return 0
                }
                if (Number(this.data.sec) === 0) {
                    this.setData({
                        bra: '0' + (Number(this.data.bra) - 1),
                        sec: 59
                    })
                    return 0
                }
                this.setData({
                    sec: ((Number(this.data.sec) - 1) > 9 ? (Number(this.data.sec) -
						1) : ('0' + (Number(this.data.sec) - 1)))
                })
            }, 1000)
        })
    },
    onUnload:function(){ 
        clearInterval(this.data.timer)
    },
})
